#!/usr/bin/python
#coding:utf-8

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time
import csvout
import sys

# driver = webdriver.Firefox()
driver = webdriver.PhantomJS()
# driver = webdriver.PhantomJS(executable_path="/home/gtmer/spider/phantomjs-2.1.1-linux-x86_64/bin/phantomjs")
url = 'https://stackoverflow.com/search?q=' + sys.argv[1]
#max load time
driver.set_page_load_timeout(10)
driver.get(url)
time.sleep(5)

# time.sleep(10)
# try:
#     element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'lbPagerTitle')))
# finally:
#time.sleep(5)
#只能找到element，不能定位到text()[2]
try:
    element = WebDriverWait(driver, 10).until(EC.presence_of_element_located(By.find_element_by_xpath('//*[@id="mainbar"]/div[2]/h2')))
    res = driver.find_element_by_xpath('//*[@id="mainbar"]/div[2]/h2').text
except:
    #如果找不到就报错，此时数值为0
    num = None
else: 
    num = filter(lambda x: x.isdigit(), res)
finally:
    outdic = {
        'stackoverflow_num': num
    }
    outli = ['stackoverflow_num', num, driver.current_url]
    csvout.list2csv(outli)
    print(outli)
    driver.close()

# if res is None:
#     num = 0
# else:
#     num = filter(lambda x: x.isdigit(), res)
